var cdn = 'http://img.zy52.cn/';
var api = 'http://ejp.zy52.cn/';
// var api = 'http://127.0.0.9/';
var token = getItem('token');
var class_name = 'toast-top-center';
if (window.innerWidth < 768) {
    class_name = 'toast-top-full-width';
}
toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: class_name,
    showMethod: 'slideDown',
    timeOut: 3000,
    hideMethod: 'slideUp',
    closeMethod: 'slideUp',
    hideDuration: 400,
    extendedTimeOut: 2000
};

$.ajaxSetup({
    data: {pc_token: token},
    dataType: 'json',
    error: function (xhr, type) {
        if (typeof btn != "undefined") {
            btn.ladda('stop');
        }
        toastr.error(xhr.status + '  ' + xhr.responseText);
    }
});

////////////////////////////////////////////

function logout() {
    localStorage.removeItem('token');
    parent.location.href = '/';
}

function clickEdit(obj, param, callback) {
    var tag = obj.firstChild.tagName;

    if (typeof (tag) != "undefined" && tag.toLowerCase() == "input") {
        return;
    }

    /* 保存原始的内容 */
    var org = obj.innerHTML;
    var val = window.ActiveXObject ? obj.innerText : obj.textContent;

    /* 创建一个输入框 */
    var txt = document.createElement("INPUT");
    txt.value = (val == 'N/A') ? '' : val;
    txt.className = 'text textpadd';
    if (obj.offsetWidth > 12) {
        txt.style.width = (obj.offsetWidth - 12) + "px";
    } else {
        txt.style.width = obj.offsetWidth + "px";
    }
    if ($(obj).siblings(".edit_icon")) {
        $(obj).siblings(".edit_icon").hide();
    }
    /* 隐藏对象中的内容，并将输入框加入到对象中 */
    obj.innerHTML = "";
    obj.appendChild(txt);
    txt.focus();

    /* 编辑区输入事件处理函数 */
    txt.onkeypress = function (e) {
        var evt = (typeof e == "undefined") ? window.event : e;
        var obj = document.all ? evt.srcElement : evt.target;

        if (evt.keyCode == 13) {
            obj.blur();
            return false;
        }

        if (evt.keyCode == 27) {
            obj.parentNode.innerHTML = org;
        }
    };

    txt.onblur = function (e) {
        if (trim(txt.value).length > 0 && txt.value != org) {
            if (typeof callback == 'function') {
                param.value = txt.value;
                callback(param, function (res) {
                    if (res.msg) {
                        toastr.error(res.msg, {time: 2000});
                    }
                    obj.innerHTML = (res.msg) ? org : res.content;
                });
            }
        } else {
            obj.innerHTML = org;
        }
    };
}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    var strValue = "";
    if (r != null) {
        strValue = unescape(r[2]);
    }
    return strValue;
}

function checkMobile(no) {
    no = no + '';
    return (no.length == 11 && /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/.test(no));
}

function checkToken(data) {
    if (event && event.target) {
        var res = JSON.parse(event.target.response);
    } else {
        res = data;
    }

    if (res.ret == -1) {
        localStorage.removeItem('token');
        location.href = '/';
    } else if (res.ret > 0) {
        toastr.error(res.msg);
    }
}

function getItem(key) {
    var ls = localStorage;
    if (ls) {
        var v = ls.getItem(key);
        if (!v) {
            return;
        }
        if (v.indexOf('obj-') === 0) {
            v = v.slice(4);
            return JSON.parse(v);
        } else if (v.indexOf('str-') === 0) {
            return v.slice(4);
        }
    }
}

function setItem(key, value) {
    if (arguments.length === 2) {
        var v = value;
        if (typeof v == 'object') {
            v = JSON.stringify(v);
            v = 'obj-' + v;
        } else {
            v = 'str-' + v;
        }
        var ls = localStorage;
        if (ls) {
            ls.setItem(key, v);
        }
    }
}

/**
 * 七牛前端上传 弹窗提醒依赖qiniu.min.js
 * @param file
 * @param complete  上传完成回调
 * @param error     错误回调
 * @param next      分片上传回调
 * @param token     七牛上传token
 */
function qiniu_upload(file, token, complete, error, next) {
    var finishedAttr = [];
    var compareChunks = [];
    var observable;
    if (file) {
        var key = (new Date()).valueOf().toString() + Math.random().toString().slice(2, 8);
        var config = {
            useCdnDomain: true,
            region: qiniu.region.z2,
        };
        var putExtra = {
            fname: "",
            params: {},
            mimeType: ["image/png", "image/jpg", "image/jpeg", "image/gif", "video/mp4"]
        };
        var html = '<div class="loading-spiner">\n' +
            '            <div class="sk-spinner sk-spinner-fading-circle">\n' +
            '                <div class="sk-circle1 sk-circle"></div>\n' +
            '                <div class="sk-circle2 sk-circle"></div>\n' +
            '                <div class="sk-circle3 sk-circle"></div>\n' +
            '                <div class="sk-circle4 sk-circle"></div>\n' +
            '                <div class="sk-circle5 sk-circle"></div>\n' +
            '                <div class="sk-circle6 sk-circle"></div>\n' +
            '                <div class="sk-circle7 sk-circle"></div>\n' +
            '                <div class="sk-circle8 sk-circle"></div>\n' +
            '                <div class="sk-circle9 sk-circle"></div>\n' +
            '                <div class="sk-circle10 sk-circle"></div>\n' +
            '                <div class="sk-circle11 sk-circle"></div>\n' +
            '                <div class="sk-circle12 sk-circle"></div>\n' +
            '            </div>\n' +
            '        </div>';

        if (typeof (error) != 'function') {
            error = function (err) {
                $('.loading-spiner').addClass('hidden');
                toastr.error(err.error);
            };
        }

        if (typeof (complete) != 'function') {
            complete = function (res) {
                return res.key;
            };
        }

        if (typeof (next) != 'function') {
            next = function (response) {
                var chunks = response.chunks || [];
                var total = response.total;
                // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
                for (var i = 0; i < chunks.length; i++) {
                    if (chunks[i].percent === 0 || finishedAttr[i]) {
                        continue;
                    }
                    if (compareChunks[i].percent === chunks[i].percent) {
                        continue;
                    }
                    if (chunks[i].percent === 100) {
                        finishedAttr[i] = true;
                    }
                }
                //console.log(total.percent);
                compareChunks = chunks;
            };
        }
        if ($('.loading-spiner').length == 0) {
            $('#page-wrapper').append(html);
        } else {
            $('.loading-spiner').removeClass('hidden');
        }

        observable = qiniu.upload(file, key, token, putExtra, config);
        var subscription = observable.subscribe(next, error, complete);//控制句柄
    }
}

function getType(file) {
    var filename = file;
    var index1 = filename.lastIndexOf(".");
    var index2 = filename.length;
    return filename.substring(index1, index2);
}

$(function () {
    //登录页面外检查token
    if (location.pathname == '/index.html') {
        if (token && token.length > 30) {
            $.ajax({
                type: 'POST',
                url: api + 'index/checkPcToken',
                success: function (data) {
                    if (data.ret == 0) {
                        toastr.options.onHidden = function () {
                            location.href = '/home.hrml';
                        };
                        localStorage.removeItem('token');
                    }
                },
                error: function (xhr, type) {
                    toastr.error('网络异常,请稍后再试');
                }
            });
        }
    }

    //阻止重复动画
    $('.modal').on('hidden.bs.modal', function () {
        $('#page-wrapper > .wrapper-content').removeClass('fadeInRight');
    });
});
